package handler

import (
	"context"
	"errors"
	"fmt"
	pb "mpps/services/srv-ProgramUpload/proto"
	common "mpps/tools/common"
	"mpps/tools/repository/dao"
	"mpps/tools/repository/dao/program"
)

type ProgramUpload struct {
}

func NewProgramUpload() *ProgramUpload {
	return &ProgramUpload{}
}

// Call is a single request handler called via client.Call or the generated client code
func (c *ProgramUpload) Call(ctx context.Context, req *pb.Request, rsp *pb.Response) error {
	if len(req.Mode) <= 0 || len(req.FileType) <= 0 || len(req.Version) <= 0 {
		return errors.New(common.ErrParamsValidation.Message)
	}
	if req.Mode != program.Dev.String() && req.Mode != program.Preview.String() && req.Mode != program.Prod.String() {
		return errors.New(common.ErrParamsValidation.Message)
	}
	if req.FileType != program.Js.String() && req.FileType != program.Program.String() {
		return errors.New(common.ErrParamsValidation.Message)
	}
	if req.FileType == program.Program.String() && len(req.ProgramId) <= 0 {
		return errors.New(common.ErrParamsValidation.Message)
	}
	if req.FileType == program.Js.String() {
		req.ProgramId = ""
	}
	model := program.MiniProgram{
		ProgramId: req.ProgramId,
		Mode:      req.Mode,
		FileName:  req.FileName,
		FileType:  req.FileType,
		FileId:    req.FileId,
		Version:   req.Version,
	}

	model.FileId = common.Md5(fmt.Sprintf("%v-%v-%v", model.FileType, model.Mode, model.Version))

	result := dao.GetDB(ctx).Model(&program.MiniProgram{}).Create(&model)
	if result.RowsAffected > 0 {
		rsp.Code = int32(common.OK.Code)
		rsp.Msg = common.OK.Message
		rsp.FileId = model.FileId
	} else {
		return errors.New(common.ErrPostUpload.Message)
	}
	return nil
}
